//
//  CommonDatabaseAccess.m
//  TopGirls
//
//  Created by Khang on 9/26/13.
//
//

#import "CommonDatabaseAccess.h"

static CommonDatabaseAccess* gCommonDatabaseAccess = nil;

@interface CommonDatabaseAccess ()

@property (nonatomic, strong) NSString* dbName;
@property (nonatomic, strong) FMDatabase* dbManager;

@end


@implementation CommonDatabaseAccess

+ (CommonDatabaseAccess *)shareCommonDatabaseAccess {
    if (gCommonDatabaseAccess == nil) {
        gCommonDatabaseAccess = [[CommonDatabaseAccess alloc] init];
    }
    return gCommonDatabaseAccess;
}

- (id)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)dealloc {
    [self closeDatabase:self.dbName];
}

- (NSString *)checkDatabase:(NSString *)dbname {
    NSArray* documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentDir = [documentPaths objectAtIndex:0];
    NSString* databasePath = [documentDir stringByAppendingPathComponent:dbname];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    BOOL success = [fm fileExistsAtPath:databasePath];
    if (!success) {
        NSString* databaseFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
        [fm copyItemAtPath:databaseFromApp toPath:databasePath error:nil];
    }
    
    return databasePath;
}

- (BOOL)openDatabase:(NSString *)dbname {
    if (self.dbName) {
        [self closeDatabase:self.dbName];
    }
    
    self.dbName = dbname;
    self.dbManager = [FMDatabase databaseWithPath:[self checkDatabase:self.dbName]];
    return [self.dbManager open];
}

- (BOOL)closeDatabase:(NSString *)dbname {
    if (dbname && [dbname isEqualToString:self.dbName]) {
        BOOL result = [self.dbManager close];
        self.dbName = nil;
        self.dbManager = nil;
        
        return result;
    }
    return NO;
}

- (BOOL)isOpening:(NSString *)dbname {
    if (dbname && [dbname isEqualToString:self.dbName]) {
        return YES;
    }
    return NO;
}

- (NSArray*)executeSelectAllWhere:(NSDictionary*)conditions {
    if (self.dbName && self.dbManager) {
        
    }
    return nil;
}

- (BOOL)executeInsertRecord:(NSDictionary*)record {
    if (self.dbName && self.dbManager) {
        
    }
    return NO;
}

- (BOOL)executeInsertRecords:(NSArray*)records {
    if (self.dbName && self.dbManager) {
        
    }
    return NO;
}

- (BOOL)executeUpdateValue:(NSDictionary*)value where:(NSDictionary*)conditions {
    if (self.dbName && self.dbManager) {
        
    }
    return NO;
}

- (BOOL)executeDeleteRecordWhere:(NSDictionary*)conditions {
    if (self.dbName && self.dbManager) {
        
    }
    return NO;
}

- (BOOL)executeDeleteAllRecords {
    if (self.dbName && self.dbManager) {
        
    }
    return NO;
}


@end
